from django.http import HttpResponse
from django.core.serializers import serialize

from ...models.chat_menu import ChatMenu

import json


def menu_list(request):
    all_chatmenu_obj = ChatMenu.objects.all().order_by('sort_num')

    json_data_str = serialize('json', all_chatmenu_obj)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def menu_save(request):
    '''
    save
    post
    body = {
        "name": "SD 绘画",
        "icon": "/images/menu/sd.png",
        "url": "/sd",
        "sort_num": 3,
        "enabled": false,
        "id": 3,
        "last_used_at": ""
    }
    '''

    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 删除没必要的数据
        try:
            del json_obj['last_used_at']
        except:
            pass

        # 查询数据
        if "id" in json_obj:
            chatmenu_instance_list = ChatMenu.objects.filter(id=json_obj['id'])
            if chatmenu_instance_list:
                chatmenu_instance = chatmenu_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            chatmenu_instance = ChatMenu()

        # 保存数据
        for key, value in json_obj.items():
            code_str = "chatmenu_instance.%s = '%s'" % (key, value)
            exec(code_str)

        try:
            chatmenu_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def menu_enable(request):
    '''
    post
    body = {
        "id": 3,
        "enabled": true
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            ChatMenu.objects.filter(id=json_obj['id']).update(enabled=json_obj['enabled'])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "数据保存失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def menu_sort(request):
    '''
    {
        "ids": [
            1,
            18,
            17,
            20
        ],
        "sorts": [
            1,
            2,
            3,
            4
        ]
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            for index, ids in enumerate(json_obj['ids']):
                ChatMenu.objects.filter(id=ids).update(sort_num=json_obj['sorts'][index])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "数据库数据更新失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def menu_remove(request):
    re_id = request.GET.get('id')
    try:
        del_obj = ChatMenu.objects.get(id=re_id)
        del_obj.delete()

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": "数据删除失败！"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

